//使用异步做for循环
const fs = require('fs');
const path = require('path');

//判断是否为文件夹
async function isdir(lujing, filename) {
    return new Promise((resolve, reject) => {
        fs.stat(lujing, (error, stats) => {
            if (error) {
                console.log(error);
                reject(error);
                return;
            }
            if (stats.isDirectory()) {
                resolve([lujing, filename]);
            } else {
                resolve(false);
            }
            // if (stats.isFile()) {
            //     resolve([false,lujing]);
            // } 
        })
    })
}

//判断是否为文件
async function isfile1(lujing, filename) {
    return new Promise((resolve, reject) => {
        fs.stat(lujing, (error, stats) => {
            if (error) {
                console.log(error);
                reject(error);
                return;
            }
            if (stats.isFile()) {
                resolve([lujing, filename]);
            } else {
                resolve(false);
            }
        })
    })
}

let dirarr = [];
let dirarr2 = [];
async function main(pathdir) {
    return new Promise((resolve, reject) => {
        // var pathdir = 'D:/s7程序备份'
        fs.readdir(pathdir, async(err, data) => {

            if (err) {
                console.log(err);
                return;
            }
            // console.log('data', data)
            for (var i = 0; i < data.length; i++) {

                let path2 = path.join(pathdir, data[i])
                let panduan = await isdir(path2, data[i])
                let isfile = await isfile1(path2, data[i])
                if (isfile) {
                    dirarr.push(isfile)
                }
                if (panduan) {
                    // console.log('panduan', panduan)
                    dirarr2.push(panduan)
                    await main(path2)
                }

            }
            // console.log(dirarr)
            resolve([dirarr, dirarr2])
        })

    })
}

module.exports = main;